home *** CD-ROM | disk | FTP | other *** search
- Path: isonews.bbn.hp.com!hpbblb!news
- From: Matthias Dittrich <matti>
- Newsgroups: comp.lang.c
- Subject: Re: How do I round and truncate floats to integers?
- Date: 21 Feb 1996 09:47:27 GMT
- Organization: Hewlett-Packard Co.
- Message-ID: <4gepnf$jse@hpbblb.bbn.hp.com>
- References: <4g009b$c2n@news.tuwien.ac.at>
- NNTP-Posting-Host: trabant.bbn.hp.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.1N (X11; I; HP-UX A.09.07 9000/712)
- X-URL: news:4g009b$c2n@news.tuwien.ac.at
-
- sor@rs6.iaee.tuwien.ac.at (Evgeni Sorokin) wrote:
- >Hello!
- >
- >I am myself ashamed of posting such stupid questions, but FAQ's and
- >books that I've found assume this to be too evident.
- >
- >Given a float (double, to be exact) how do I
- >
- >1) round it to nearest integer (forget 0.5 problem for the moment) and
- >2) truncate it to the integer?
- >
- >I browsed include directories of my compilers (Turbo C and GNU) and
- >have not found passing functions taking floats and returning
- >integers. If typecasting is supposed to do the trick, then how do I
- >distinguish cases 1) and 2)?
- >...
- A typecast to integer truncates your floating number, this is not a trick.
- Negative numbers are truncated in the same way, that means -2.7 assigned to
- an integer gives 2 as result. I'm not sure here if this is defined behaviour
- or compiler dependent.
- To round you must distinguish these two cases. Add 0.5 to a positive floating
- number and subtract 0.5 from a negative one before truncating it.
-
- Good luck,
- Matthias
-
-